package com.study.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class VolatoleAtomicityDemo {
    private volatile static int inc = 0;
    private volatile static int incLock = 0;
    private static final Lock lock = new ReentrantLock();
    private static AtomicInteger incAtomic = new AtomicInteger(0);

    public void increase() {
        //volatile 只能保证可见性不能保证原子性,每次运行结果都不同
        inc++;
        /*
        inc++ 其实是一个复合操作，包括三步：
        读取 inc 的值。
        对 inc 加 1。
        将 inc 的值写回内存。
         */
    }

    public void increaseLock() {
        lock.lock();
        try {
            incLock++;
        } finally {
            lock.unlock();
        }
    }

    public void increaseAtomic() {
        //可以保证可见性，以及原子性
        incAtomic.getAndIncrement();
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        VolatoleAtomicityDemo volatoleAtomicityDemo = new VolatoleAtomicityDemo();
        for (int i = 0; i < 5; i++) {
            threadPool.execute(() -> {
                for (int j = 0; j < 500; j++) {
                    volatoleAtomicityDemo.increase();
                    volatoleAtomicityDemo.increaseAtomic();
                    volatoleAtomicityDemo.increaseLock();
                }
            });
        }
        // 等待1.5秒，保证上面程序执行完成
        Thread.sleep(1500);
        System.out.println(inc);
        System.out.println(incAtomic);
        System.out.println(incLock);
        threadPool.shutdown();
    }
}
